package com.heima.heima_netty.nio.c3;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

import static com.heima.heima_netty.nio.c1.ByteBufferUtil.debugAll;
import static com.heima.heima_netty.nio.c1.ByteBufferUtil.debugRead;

/**
 * @author felix
 * @date 2024/9/10 14:54
 *
 */
@Slf4j
public class ServerSelector03 {
    public static void split(ByteBuffer source){
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if(source.get(i)=='\n'){
                int length = i + 1 - source.position();
                ByteBuffer buffer = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    buffer.put(source.get());
                }
                debugAll(buffer);
            }
        }
        source.compact();
    }

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // selector要配合非阻塞模式使用
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8089));

        // 1.创建一个selector
        Selector selector = Selector.open();
        // 2.将channel注册到selector上
        SelectionKey sscKey = ssc.register(selector, 0, null);
        log.debug("register Key:{}",sscKey);
        // 3.指定selector要监听的事件类型
        sscKey.interestOps(SelectionKey.OP_ACCEPT);

        /**
         * 注册集合与事件集合
         * 0. SelectionKey与SocketChannel一一对应
         * 1. 当channel注册到selector上时，会将key放入注册集合中
         * 2. 当key监听到事件发生时，会将注册集合中该对象复制进事件集合中
         * 3. 事件集合中的对象不会自动删除，事件处理结束后应手动进行删除
         */
        while (true){
            // 4.启动selector监听
            // 没有事件时阻塞，有事件时不会阻塞，进行处理或取消
            selector.select();
            // 5.获取监听到的事件集合
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                //6.获取事件并处理
                SelectionKey key = iterator.next();
                log.debug("获取事件监听Key:{}",key);
                iterator.remove();
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("创建读事件监听Key:{}",scKey);
                } else if (key.isReadable()) {
                    try {
                        SocketChannel sc = (SocketChannel)key.channel();
                        log.debug("监听到读事件:{}",sc);
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        int read = sc.read(buffer);
                        if(read==-1){//客户端正常断开为-1
                            key.cancel();//删除注册集合中的该事件监听对象
                        }else{
                            split(buffer);
                        }
                    } catch (IOException e) {
                        key.cancel();
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
